﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using agsXMPP.protocol.client;
using YanMsg.APCode;
using System.Windows.Interop;
using CSharpWin;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Timers;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Windows.Threading;

namespace YanMsg.View
{
    /// <summary>
    /// FriendList.xaml 的交互逻辑
    /// </summary>
    public partial class FriendList : UserControl
    {
        /// <summary>
        /// 消息来时闪烁任务栏
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="WinkIf"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern bool FlashWindow(IntPtr hWnd, bool WinkIf);
        public static vw_Yan_Chat_user myinfo = null;
        public static vw_Yan_Chat_user userinfo = null;
        private System.Timers.Timer RevMsgTimer = null;
        DispatcherTimer TimeIco = new DispatcherTimer();//图标计时器
        DispatcherTimer TimeDcl = new DispatcherTimer();//获取需要处理的单据计时器

        public FriendList()
        {
            try
            {
                UserData.ListPeople = new YanChatHelp().GetAllUser();
                myinfo = UserData.ListPeople.SingleOrDefault(D => D.UserName == Login.connection.Username);
                userinfo = UserData.ListPeople.SingleOrDefault(D => D.UserName == Login.connection.Username);

                UserData.UserNumber = myinfo.UserName;
                UserData.UserRealNumber = myinfo.UserRealName;
                //日志按钮
                //UserData.MainWindow.AddDayLog.Visibility = Visibility.Visible;

                InitializeComponent();
                Task TaskInit = new Task(TaskInitT);
                TaskInit.Start();

                //消息处理
                Login.connection.OnMessage += new MessageHandler(con_OnMessage);
                //修改个人签名事件
                DictumBox.MouseLeftButtonDown += delegate(Object o, MouseButtonEventArgs e)
                {
                    this.DictumBox.Visibility = Visibility.Collapsed;
                    this.DictumBoxText.Visibility = Visibility.Visible;
                    this.DictumBoxText.Focus();
                };

                //修改个人签名事件
                DictumBoxText.LostFocus += delegate(Object o, RoutedEventArgs e)
                {
                    this.DictumBox.Visibility = Visibility.Visible;
                    this.DictumBoxText.Visibility = Visibility.Collapsed;
                    myinfo.Usersign = this.DictumBoxText.Text.ToString();
                    MainPeopleList.ModifyPeopleTree();
                    Task task = new Task(TaskUpdateUser);
                    task.Start();
                };



                //修改个人签名事件

                //监听接收文件
                UserData.udpReceiveFile = new UdpReceiveFile(
         int.Parse("10003"));
                UserData.udpReceiveFile.RequestSendFile +=
                    new RequestSendFileEventHandler(RequestSendFile);
                UserData.udpReceiveFile.FileReceiveBuffer +=
                    new FileReceiveBufferEventHandler(FileReceiveBuffer);
                UserData.udpReceiveFile.FileReceiveComplete +=
                    new FileReceiveEventHandler(FileReceiveComplete);
                UserData.udpReceiveFile.FileReceiveCancel +=
                    new FileReceiveEventHandler(FileReceiveCancel);
                UserData.udpReceiveFile.Start();
                //监听接收文件

                //获取天气数据
                GetWeatherInfo();

                //图标计时器
                TimeIco.Tick += new EventHandler(TimeIco_Tick);
                TimeIco.Interval = TimeSpan.FromSeconds(1);   //设置刷新的间隔时间
                TimeIco.Start();

                //获取待处理数据计时器
                TimeDcl.Tick += new EventHandler(TimeDcl_Tick);
                TimeDcl.Interval = TimeSpan.FromMinutes(10);   //设置刷新的间隔时间
                TimeDcl.Start();

                GetDCL();

                //获取出差休假信息
                UserData.dtXJinfo = new User().GetDTByCommand(" SELECT CC.CRUser ,CC.remark3, CC.LeiBieName, CC.ZhuYaoShiYou FROM GR_CCXJ  CC join Pro_ZiDian ZD on CC.LeiBie=ZD.TypeNO  WHERE  getdate() BETWEEN  CAST(StarTime+ ' '+ (CASE CC.remark2 WHEN '上午' THEN '00:01:00'  ELSE '12:01:00'  END) as datetime) AND CAST(EndTime+ ' '+ (CASE LeiBieName WHEN '上午'  THEN '12:01:00'  ELSE '23:59:00'  END) as datetime)  AND ZD.Class=3 AND CC.IsComPlete='Y' ");


            }
            catch (Exception ex)
            {
                using (YanAdminNewEntities Entities = new YanAdminNewEntities())
                {
                }
            }


        }


        private void GetWeatherInfo()
        {
            string strUrl = "http://m.weather.com.cn/atad/101180101.html";
            string strReturnInfo = ChatHelp.GetRepose(strUrl);
            if (strReturnInfo != "")
            {
                JObject googleSearch = JObject.Parse(strReturnInfo);
                tbcity.Text = googleSearch["weatherinfo"]["city"].ToString();
                tbweather.Text = googleSearch["weatherinfo"]["weather1"].ToString();
                tbtemp.Text = googleSearch["weatherinfo"]["temp1"].ToString();



                tbtemp1.Text = googleSearch["weatherinfo"]["temp1"].ToString();
                tbtemp2.Text = googleSearch["weatherinfo"]["temp2"].ToString();
                tbtemp3.Text = googleSearch["weatherinfo"]["temp3"].ToString();

                tbweather1.Text = googleSearch["weatherinfo"]["weather1"].ToString();
                tbweather2.Text = googleSearch["weatherinfo"]["weather2"].ToString();
                tbweather3.Text = googleSearch["weatherinfo"]["weather3"].ToString();

                tbDate.Text = googleSearch["weatherinfo"]["date_y"].ToString() + "," + googleSearch["weatherinfo"]["week"].ToString();
                tbNongli.Text = "农历" + ChinaDate.GetMonth(DateTime.Now).ToString() + ChinaDate.GetDay(DateTime.Now).ToString();
            }

        }
        void TimeIco_Tick(object sender, EventArgs e)
        {
            if (UserData.notifyIcon.Icon != UserData.Icon_Offline)
            {
                if (UserData.strIsFlagFlash == "Y")
                {
                    if (UserData.notifyIcon.Icon == UserData.touminico)
                    {
                        UserData.notifyIcon.Icon = UserData.Msgico;
                    }
                    else
                    {
                        UserData.notifyIcon.Icon = UserData.touminico;
                    }
                }
                else
                {
                    UserData.notifyIcon.Icon = UserData.Icon_Online;
                }
            }
        }
        void TimeDcl_Tick(object sender, EventArgs e)
        {

            if (Application_Init.GetIconUserState() != "3")
            {
                GetDCL();
            }
        }


        private void GetDCL()
        {
            int intOldFormCount = int.Parse(FormCount.Text);

            string FormUrl = ConfigManger.ClientWebUrl + "Common/ComMobileAPI.ashx?Action=GetDJSSPCount&UserName=" + myinfo.UserName;
            string strReturnInfo = ChatHelp.GetRepose(FormUrl);
            if (strReturnInfo != "")
            {
                int intTZCount = int.Parse(strReturnInfo.Split('|')[0].ToString());
                FormCount.Text = intTZCount.ToString();
                if (intOldFormCount < intTZCount)
                {
                    string XXNeiRong = strReturnInfo.Split('|')[1].ToString().Trim();
                    string strUrl = ConfigManger.ClientWebUrl.Substring(7) + "login.aspx?password=" + myinfo.UserPass + "&userid=" + UserData.UserNumber;
                    string strUser = XXNeiRong.Split(',')[3].ToString();
                    if (XXNeiRong.Split(',')[2].ToString() == "接收")
                    {
                        strUser = UserData.ListPeople.Where(d => d.UserName == strUser).FirstOrDefault().UserRealName;
                    }
                    MsgManger.ShowTuiTip("你有来自[b]" + strUser + "[/b]的一个[b]" + XXNeiRong.Split(',')[0].ToString() + "[/b],[url=http://" + strUrl + "]请及时" + XXNeiRong.Split(',')[2].ToString() + "[/url]");
                    UserData.strIsFlagFlash = "Y";
                }
                if (FormCount.Text == "0")
                {
                    UserData.strIsFlagFlash = "N";
                }
            }
        }


        private void TaskUpdateUser()
        {
            new YanChatHelp().UpdateUserStatus(myinfo.UserName, myinfo.Usersign);
        }

        /// <summary>
        /// 绑定用户及组数据
        /// </summary>
        private void TaskInitT()
        {
            UserData.ListGroup = new YanChatHelp().GetUserGroups(UserData.UserNumber).OrderBy(d => d.GroupCreateUser).ToObservableCollection();
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.RootItem.ItemsSource = MainPeopleList.PeopleTree;
                GroupList.ItemsSource = UserData.ListGroup;

            }));

        }

        //消息处理事件
        void con_OnMessage(object sender, agsXMPP.protocol.client.Message msg)
        {

            //处理用户点对点聊天信息
            if (msg.Type == MessageType.chat || msg.Type == MessageType.groupchat)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    ReceiveMsg(msg);
                }));

            }
            else if (msg.Type == MessageType.headline)
            {
                if (msg.Body.ToString() == YanCommand.UpdateGroup)
                {
                    UserData.ListGroup = new YanChatHelp().GetUserGroups(UserData.UserNumber).ToObservableCollection();
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        GroupList.ItemsSource = UserData.ListGroup;
                    }));
                }
            }
            else
            {
                // YLSystemBase.BRMessage.ShowMessage(3, "系统消息", msg.Body);
            }
        }



        /// <summary>
        /// 委托向RichTextBox中添加消息
        /// </summary>
        /// <param name="Message">要添加的消息</param>
        /// <returns>返回委托事件</returns>
        public void ReceiveMsg(Message Msg)
        {
            try
            {


                string strMSGUser = Msg.From.User;
                string msgConTent = ZipHelper.GZipDecompressString(Msg.Body);
                string strGroupID = Msg.To.User;



                //将信息加载到临时RichTextBox

                Xceed.Wpf.Toolkit.RichTextBox RTemp = new Xceed.Wpf.Toolkit.RichTextBox();
                ChatManger.LoadFromRTF(RTemp, msgConTent);

                //添加信息头
                string strMSTitle = ChatManger.GetUserName(strMSGUser) + "  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                StackPanel SP = new StackPanel();
                SP.Margin = new Thickness(0, 0, 0, 4);
                TextBlock TB = new TextBlock(new Bold(new Run(strMSTitle)));
                TB.Foreground = new SolidColorBrush(Colors.Teal);
                SP.Children.Add(TB);
                BlockUIContainer BU = new BlockUIContainer(SP);

                //查找该窗口是否存在
                if (Msg.Type == MessageType.chat)
                {
                    //存到本地
                    ChatHelp.InsertChat(Msg.From.User, Msg.To.User, Msg.Body, (int)Msg.Type);


                    Chat TalkWin = null;
                    if (UserData.DictionaryChat.ContainsKey(strMSGUser))//该窗口存在
                    {
                        TalkWin = UserData.DictionaryChat[strMSGUser] as Chat;
                        //添加信息内容
                    }
                    //如果该窗口不存在，则打入托盘区消息提示状态
                    else
                    {
                        TalkWin = new Chat(strMSGUser);
                        UserData.DictionaryChat.Add(strMSGUser, TalkWin);
                        TalkWin.Show();
                        TalkWin.WindowState = System.Windows.WindowState.Minimized;
                    }
                    TalkWin.ViewMessgeBox.Document.Blocks.Add(BU);
                    //添加信息内容
                    List<Block> ListMsgBlock = new List<Block>();
                    for (int i = RTemp.Document.Blocks.Count - 1; i >= 0; i--)
                    {
                        Block q = RTemp.Document.Blocks.ElementAt(i);
                        ListMsgBlock.Add(q);
                    }
                    ListMsgBlock.Reverse();
                    TalkWin.ViewMessgeBox.Document.Blocks.AddRange(ListMsgBlock);
                    TalkWin.ViewMessgeBox.Document.Blocks.Add(new BlockUIContainer(new StackPanel { Height = 10 }));

                    TalkWin.ViewMessgeBox.ScrollToEnd();

                    if (TalkWin.WindowState == System.Windows.WindowState.Minimized)
                    {
                        //得到当前窗体的句柄
                        WindowInteropHelper Helper = new WindowInteropHelper(TalkWin);
                        IntPtr ptr = Helper.Handle;
                        FlashWindow(ptr, true);//闪烁任务栏
                    }
                }
                if (Msg.Type == MessageType.groupchat)
                {
                    GroupChat TalkWin = null;
                    if (UserData.DictionaryGroupChat.ContainsKey(strGroupID))//该窗口存在
                    {
                        TalkWin = UserData.DictionaryGroupChat[strGroupID] as GroupChat;
                        //添加信息内容
                    }
                    //如果该窗口不存在，则打入托盘区消息提示状态
                    else
                    {
                        TalkWin = new GroupChat(strGroupID);
                        UserData.DictionaryGroupChat.Add(strGroupID, TalkWin);
                        TalkWin.Show();
                        TalkWin.WindowState = System.Windows.WindowState.Minimized;
                    }
                    TalkWin.ViewMessgeBox.Document.Blocks.Add(BU);
                    //添加信息内容
                    List<Block> ListMsgBlock = new List<Block>();
                    for (int i = RTemp.Document.Blocks.Count - 1; i >= 0; i--)
                    {
                        Block q = RTemp.Document.Blocks.ElementAt(i);
                        ListMsgBlock.Add(q);
                    }
                    ListMsgBlock.Reverse();
                    TalkWin.ViewMessgeBox.Document.Blocks.AddRange(ListMsgBlock);
                    TalkWin.ViewMessgeBox.ScrollToEnd();
                    if (TalkWin.WindowState == System.Windows.WindowState.Minimized)
                    {
                        //得到当前窗体的句柄
                        WindowInteropHelper Helper = new WindowInteropHelper(TalkWin);
                        IntPtr ptr = Helper.Handle;
                        FlashWindow(ptr, true);//闪烁任务栏
                    }
                }
            }
            catch (Exception ex)
            {

                MsgManger.Show(ex.Message);
            }


        }


        public void AddTree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (FriendLists.SelectedItem is TreeUser)
            {
                TreeUser User = FriendLists.SelectedItem as TreeUser;
                if (!UserData.DictionaryChat.ContainsKey(User.UserName))
                {
                    Chat NewChat = new Chat(User.UserName);
                    UserData.DictionaryChat.Add(User.UserName, NewChat);
                    NewChat.Activate();
                    NewChat.Topmost = true;
                    NewChat.Show();
                }
                else
                {
                    //得到当前窗体的句柄
                    Chat TalkWin = UserData.DictionaryChat[User.UserName] as Chat;
                    WindowInteropHelper Helper = new WindowInteropHelper(TalkWin);
                    IntPtr ptr = Helper.Handle;
                    FlashWindow(ptr, true);//闪烁任务栏
                }
            }
        }

        //删除讨论组
        private void delGroup_Click(object sender, RoutedEventArgs e)
        {
            MenuItem Menu = sender as MenuItem;
            YanChat_Group dgp = UserData.ListGroup.SingleOrDefault(d => d.ID.ToString() == Menu.Tag.ToString());
            UserData.ListGroup.Remove(dgp);
            new TBYanChat_Group().Delete(dgp);
        }

        //添加讨论组
        private void addGroup_Click(object sender, RoutedEventArgs e)
        {
            GroupManger GroupView = new GroupManger();
            GroupView.Show();
        }

        //进入讨论组界面
        private void JoinGroup_Click(object sender, RoutedEventArgs e)
        {
            MenuItem Menu = sender as MenuItem;
            string strGroupID = Menu.Tag.ToString();
            ToGroupChat(strGroupID);

        }
        //退出讨论组界面
        private void ExitGroup_Click(object sender, RoutedEventArgs e)
        {
            MenuItem Menu = sender as MenuItem;
            string strGroupID = Menu.Tag.ToString();
            YanChat_Group dgp = UserData.ListGroup.SingleOrDefault(d => d.ID.ToString() == Menu.Tag.ToString());
            new YanChatHelp().ExitGroup(strGroupID, UserData.UserNumber);
            UserData.ListGroup.Remove(dgp);
        }
        //双击讨论组
        private void GroupList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string strGroupID = ((sender as ListBox).SelectedItem as YanChat_Group).ID.ToString();
            ToGroupChat(strGroupID);
        }



        private void ToGroupChat(string strGroupID)
        {
            if (!UserData.DictionaryGroupChat.ContainsKey(strGroupID))
            {
                GroupChat NewGroupChat = new GroupChat(strGroupID);
                UserData.DictionaryGroupChat.Add(strGroupID, NewGroupChat);
                NewGroupChat.Activate();
                NewGroupChat.Topmost = true;
                NewGroupChat.Show();
            }
            else
            {
                //得到当前窗体的句柄
                GroupChat TalkWin = UserData.DictionaryGroupChat[strGroupID] as GroupChat;
                WindowInteropHelper Helper = new WindowInteropHelper(TalkWin);
                IntPtr ptr = Helper.Handle;
                FlashWindow(ptr, true);//闪烁任务栏
            }
        }

        private void FriendList_Unloaded(object sender, RoutedEventArgs e)
        {
            Login.connection.Close();
        }



        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgTX_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            GetTX TXView = new GetTX();
            TXView.Show();
        }

        #region udpReceiveFile Events

        private void FileReceiveCancel(
            object sender, FileReceiveEventArgs e)
        {
            foreach (Chat TalkWin in UserData.DictionaryChat.Values)
            {
                string md5 = string.Empty;
                if (e.ReceiveFileManager != null)
                {
                    md5 = e.ReceiveFileManager.MD5;
                }
                else
                {
                    md5 = e.Tag.ToString();
                }

                FileTransfersItem item = TalkWin.SendFileControl.Search(md5);

                this.Dispatcher.Invoke(new Action(() =>
                {
                    TalkWin.SendFileControl.RemoveItem(item);
                    TalkWin.HideSendFile();
                    TalkWin.ShowFileMsg("对方取消发送文件: " + item.FileName);
                }));
            }
        }

        private void FileReceiveComplete(
            object sender, FileReceiveEventArgs e)
        {
            string strMSGUser = UserData.ListPeople.SingleOrDefault(d => d.UserIPAdress == e.ReceiveFileManager.RemoteIP.Address.ToString()).UserName;
            if (UserData.DictionaryChat.ContainsKey(strMSGUser))//该窗口存在
            {
                Chat TalkWin = UserData.DictionaryChat[strMSGUser] as Chat;
                this.Dispatcher.Invoke(new Action(() =>
                {
                    TalkWin.SendFileControl.RemoveItem(e.ReceiveFileManager.MD5);
                    TalkWin.HideSendFile();
                    TalkWin.ShowFileMsg("文件: " + e.ReceiveFileManager.Name + " 接收完成");
                }));
            }
        }

        private void FileReceiveBuffer(
            object sender, FileReceiveBufferEventArgs e)
        {
            string strMSGUser = UserData.ListPeople.SingleOrDefault(d => d.UserIPAdress == e.ReceiveFileManager.RemoteIP.Address.ToString()).UserName;
            if (UserData.DictionaryChat.ContainsKey(strMSGUser))//该窗口存在
            {
                Chat TalkWin = UserData.DictionaryChat[strMSGUser] as Chat;
                FileTransfersItem item = TalkWin.SendFileControl.Search(
                    e.ReceiveFileManager.MD5);
                if (item != null)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        item.TotalTransfersSize += e.Size;
                    }));
                }
            }
        }

        private void RequestSendFile(
            object sender, RequestSendFileEventArgs e)
        {
            TraFransfersFileStart traFransfersFileStart = e.TraFransfersFileStart;

            this.Dispatcher.Invoke(new Action(() =>
            {
                string strMSGUser = UserData.ListPeople.SingleOrDefault(d => d.UserIPAdress == e.RemoteIP.ToString().Split(':')[0]).UserName;
                Chat TalkWin = null;
                if (UserData.DictionaryChat.ContainsKey(strMSGUser))//该窗口存在
                {
                    TalkWin = UserData.DictionaryChat[strMSGUser] as Chat;
                }
                else
                {
                    TalkWin = new Chat(strMSGUser);
                    UserData.DictionaryChat.Add(strMSGUser, TalkWin);
                    TalkWin.Show();
                    TalkWin.WindowState = System.Windows.WindowState.Minimized;
                }
                TalkWin.ShowSendFile();
                FileTransfersItem item = TalkWin.SendFileControl.AddItem(
                 traFransfersFileStart.MD5,
                 "接收文件",
                 traFransfersFileStart.FileName,
                 traFransfersFileStart.Image,
                 traFransfersFileStart.Length,
                 FileTransfersItemStyle.ReadyReceive);

                item.BaseColor = System.Drawing.Color.DarkGoldenrod;
                item.BorderColor = System.Drawing.Color.FromArgb(64, 64, 0);
                item.ProgressBarBarColor = System.Drawing.Color.Gold;
                item.ProgressBarBorderColor = System.Drawing.Color.Olive; ;
                item.ProgressBarTextColor = System.Drawing.Color.Olive; ;

                item.Tag = e;
                item.SaveButtonClick += new EventHandler(ItemSaveButtonClick);
                item.SaveToButtonClick += new EventHandler(ItemSaveToButtonClick);
                item.RefuseButtonClick += new EventHandler(ItemRefuseButtonClick);
            }));
        }

        private void ItemRefuseButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item = sender as FileTransfersItem;
            RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
            rse.Cancel = true;
            FileTansfersContainer Container = item.Parent as FileTansfersContainer;
            Container.RemoveItem(item);
            item.Dispose();
            UserData.udpReceiveFile.AcceptReceive(rse);
        }

        private void ItemSaveToButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item = sender as FileTransfersItem;
            RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                rse.Path = fbd.SelectedPath;
                //AppendLog(string.Format(
                //    "同意接收文件 {0}。",
                //    rse.TraFransfersFileStart.FileName), false);
                ControlTag tag = new ControlTag(
                    rse.TraFransfersFileStart.MD5,
                    rse.TraFransfersFileStart.FileName,
                    rse.RemoteIP);
                item.Tag = tag;
                item.Style = FileTransfersItemStyle.Receive;
                item.CancelButtonClick += new EventHandler(ItemCancelButtonClick);
                item.Start();

                UserData.udpReceiveFile.AcceptReceive(rse);
            }
        }

        private void ItemSaveButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item = sender as FileTransfersItem;
            RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;

            //rse.Path = UserData.AppDirectory;
            rse.Path = ConfigManger.ServerRevDefaultPah;
            //AppendLog(string.Format(
            //       "同意接收文件 {0}。",
            //       rse.TraFransfersFileStart.FileName), false);
            ControlTag tag = new ControlTag(
                rse.TraFransfersFileStart.MD5,
                rse.TraFransfersFileStart.FileName,
                rse.RemoteIP);
            item.Tag = tag;
            item.Style = FileTransfersItemStyle.Receive;
            item.CancelButtonClick += new EventHandler(ItemCancelButtonClick);
            item.Start();

            UserData.udpReceiveFile.AcceptReceive(rse);
        }

        private void ItemCancelButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item = sender as FileTransfersItem;
            ControlTag tag = item.Tag as ControlTag;
            UserData.udpReceiveFile.CancelReceive(tag.MD5, tag.RemoteIP);
            FileTansfersContainer Container = item.Parent as FileTansfersContainer;
            Container.RemoveItem(item);
            item.Dispose();
            //AppendLog(string.Format(
            //   "取消接收文件 {0}。",
            //   tag.FileName), false);
        }

        #endregion



        //表单中心
        private void ImageForm_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string strUrl = "";
            try
            {
                strUrl = ConfigManger.ClientWebUrl + "login.aspx?password=" + myinfo.UserPass + "&userid=" + UserData.UserNumber;
                System.Diagnostics.Process.Start(strUrl);
            }
            catch (Exception)
            {
                strUrl = ConfigManger.ClientWebUrl + "login.aspx?password=" + myinfo.UserPass + "&userid=" + UserData.UserNumber;
                Process ps = new Process();
                ps.StartInfo.FileName = "iexplore.exe";
                ps.StartInfo.Arguments = strUrl;
                ps.Start();
            }

        }



        /// <summary>
        /// 消息中心
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_XXZXButtonDown(object sender, MouseButtonEventArgs e)
        {
            MsgManger.ShowWindows(new MsgBox());
            //MsgManger.ShowWindows(new FileBox());
        }


        //右键发送信息
        private void MnSend_Click(object sender, RoutedEventArgs e)
        {
            MenuItem Menu = sender as MenuItem;
            string strMSGUser = Menu.Tag.ToString();
            Chat TalkWin = null;
            if (UserData.DictionaryChat.ContainsKey(strMSGUser))//该窗口存在
            {
                TalkWin = UserData.DictionaryChat[strMSGUser] as Chat;
                //添加信息内容
            }
            //如果该窗口不存在，则打入托盘区消息提示状态
            else
            {
                TalkWin = new Chat(strMSGUser);
                UserData.DictionaryChat.Add(strMSGUser, TalkWin);
                TalkWin.Show();
            }
        }

        //右键查看人员信息
        private void MnViewPeopleInfo_Click(object sender, RoutedEventArgs e)
        {
            MsgManger.Show("正在开发O(∩_∩)O");
        }

        //右键查看人员聊天记录
        private void MnViewPeopleChat_Click(object sender, RoutedEventArgs e)
        {
            MenuItem Menu = sender as MenuItem;
            string strMSGUser = Menu.Tag.ToString();
            ChatHistory history = new ChatHistory(strMSGUser);
            history.Topmost = true;
            history.Show();
        }

        private void Imageinfo_MouseEnter(object sender, MouseEventArgs e)
        {
            Image user = sender as Image;
            string strUser = user.Tag.ToString();
            userinfo = UserData.ListPeople.SingleOrDefault(D => D.UserName == strUser);
            popususer.DataContext = userinfo;
            popususer.PlacementTarget = user;
            popususer.IsOpen = true;
        }

        private void Imageinfo_MouseLeave(object sender, MouseEventArgs e)
        {
            popususer.IsOpen = false;
        }




    }
}
